package com.huihui.activity.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.datamanager.AppManager;
import com.huihui.eventbus.SettinNickNameEvent;
import com.huihui.eventbus.SettingUserInfoSuccess;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.CropPhotoUtil;
import com.huihui.utils.IntentUtils;
import com.huihui.utils.LoadImageUtil;
import com.huihui.widget.SelectPicPopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * 设置个人信息
 */
public class MineSettingActivity extends BaseActivity {

    private RelativeLayout head_setting;
    private CircleImageView head_img;
    private RelativeLayout name_setting;
    private TextView name;
    private RelativeLayout sex_setting;
    private TextView sex;
    private String nickName;
    private boolean isEdit = false;
    //自定义的弹出框类
    SelectPicPopupWindow menuWindow;

    private static final int CODE_REQUEST_CAMERA_PHOTO = 200;
    private static final int CODE_REQUEST_CROP_PHOTO = 201;
    private static final int CODE_REQUEST_PICTURE = 202;
    private String mCurrentPhotoName;
    private String mNewCurrentPhotoName;
    private String path;
    private String key = "";
    private File file;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_setting2);
//        getSupportActionBar().setTitle(R.string.setting_userinfo);
        titleView.setText(R.string.setting_userinfo);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        //设置已经有的
        UserInfo userInfo = AppManager.getUserInfo();
        if (userInfo != null) {
            //设置
            nickName = userInfo.getNick_name();
            name.setText(nickName);
            if (userInfo.getUser_sex() == 1) {
                sexType = 1;
                sex.setText("男");
            } else {
                sex.setText("女");
                sexType = 0;
            }
            LoadImageUtil.displayImage(getContext(), userInfo.getHead_img(), head_img);
        }
    }

    private void initView() {
        head_setting =  findViewById(R.id.head_setting);
        head_img =  findViewById(R.id.head_img);
        name_setting =  findViewById(R.id.name_setting);
        name =  findViewById(R.id.name);
        sex_setting =  findViewById(R.id.sex_setting);
        sex =  findViewById(R.id.sex);
    }

    private void initListener() {
        head_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChoosePicDialog();
            }
        });
        name_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.gotoSettingNickNameActivity(getContext());
            }
        });

        sex_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实例化SelectPicPopupWindow
                menuWindow = new SelectPicPopupWindow(MineSettingActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(MineSettingActivity.this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
            }
        });
    }


    @Override
    public void onBackPressed() {
//        String str = "headphoto/";
//        String name = getUUID32();
//        key = str + name + ".jpg";
//        upload(key, path);
//        if (getUserInfo() != null && isEdit) {
//            updateUserInfo(key);
//        } else {
//            super.onBackPressed();
//        }
        //当前用户图像url  不为空表示修改过头像
//        if (TextUtils.isEmpty(path)) {
//
//        } else {
//            String str = "headphoto/";
//            String name = getUUID32();
//            key = str + name + ".jpg";
//            upload(key, path);
//        }
        if(isEdit) {
            updateUserInfo();
        }else{
            super.onBackPressed();
        }
    }

    private void updateUserInfo() {
        OkHttpRequest.getInstance().updateUser(HttpContants.updateUser, AppManager.getUserInfo().getUser_id(), sexType, nickName, file, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject != null && jsonObject.has(HttpContants.DATA)) {
                        UserInfo userInfo = AppManager.getGson().fromJson(jsonObject.getString(HttpContants.DATA), UserInfo.class);
                        if (userInfo != null) {
                            AppManager.setUserInfo(userInfo);
                            setUserInfo(userInfo);
                            Log.d(TAG, " 更新后的头像 url = " + userInfo.getHead_img());
                            EventBus.getDefault().post(new SettingUserInfoSuccess());
                        }
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void upload(String key, String path) {
        if (!TextUtils.isEmpty(path)) {
            uploadFile(key, path);
        }
    }

    @Override
    protected void uploadFileSuccess() {
        super.uploadFileSuccess();
//        updateUserInfo(key);
    }

    private int sexType = 1;
    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            isEdit = true;
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    sexType = 1;
                    sex.setText("男");
                    break;
                case R.id.btn_pick_photo:
                    sexType = 0;
                    sex.setText("女");
                    break;
                default:
                    break;
            }


        }

    };

    private void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MineSettingActivity.this);
        builder.setTitle("添加图片");
        String[] items = {"选择本地照片", "拍照"};
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setType("image/*");//选择图片
                        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intentFromGallery, CODE_REQUEST_PICTURE);

                        break;
                    case 1:
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        mCurrentPhotoName = System.currentTimeMillis() + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mCurrentPhotoName)));
                        startActivityForResult(intent, CODE_REQUEST_CAMERA_PHOTO);
                        break;
                }
            }
        });
        builder.show();
    }

    /**
     * 判断是否有存储卡，有返回TRUE，否则FALSE
     *
     * @return
     */
    public static boolean isSDcardExist() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_CAMERA_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
//                if (data == null) {
//                    return;
//                }
                isEdit = true;
                File tempFile = new File(
                        Environment.getExternalStorageDirectory(),
                        mCurrentPhotoName);
                mNewCurrentPhotoName = "pz_" + mCurrentPhotoName;
                path = Environment.getExternalStorageDirectory() + File.separator + mNewCurrentPhotoName;
                CropPhotoUtil.cropRawPhoto(this, Uri.fromFile(tempFile), CODE_REQUEST_CROP_PHOTO, path, 200, 200);
//                CropPhotoUtil.cropRawPhoto(this, data.getData(), CODE_REQUEST_CROP_PHOTO, path, 200, 200);
            }
        } else if (requestCode == CODE_REQUEST_CROP_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                path = Environment.getExternalStorageDirectory() + File.separator + mNewCurrentPhotoName;
                file = new File(path);
                isEdit = true;
                LoadImageUtil.displayImage(getContext(), file, head_img);
            }
        } else if (requestCode == CODE_REQUEST_PICTURE && resultCode == Activity.RESULT_OK) {
            if (data == null) return;
            isEdit = true;
            mNewCurrentPhotoName = System.currentTimeMillis() + ".jpg";
            String outPath = Environment.getExternalStorageDirectory() + File.separator + mNewCurrentPhotoName;
            CropPhotoUtil.cropRawPhoto(this, data.getData(), CODE_REQUEST_CROP_PHOTO, outPath, 200, 200);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(SettinNickNameEvent messageEvent) {
        if (messageEvent != null) {
            nickName = messageEvent.getNickNmae();
            name.setText(messageEvent.getNickNmae());
            isEdit = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
